package com.example.weatherforecast

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.ArrayAdapter
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.example.weatherforecast.databinding.ActivityMain2Binding
import com.example.weatherforecast.weather.Weather
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.io.BufferedReader
import java.io.InputStreamReader
import com.example.weatherforecast.weather.Forecast
import java.lang.reflect.Type

class MainActivity2 : AppCompatActivity() {
    val baseURL = "    http://t.weather.itboy.net/api/weather/city/"
    private val binding by lazy { ActivityMain2Binding.inflate(layoutInflater) }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(binding.root)
        val cityCode = intent.getStringExtra("city_code")
        val queue = Volley.newRequestQueue(this)
        val stringRequest = StringRequest(baseURL + cityCode, {
            val gson = Gson()
            val WeatherType : Type = object :TypeToken<Weather>() {}.type
            val weather: Weather = gson.fromJson(it, WeatherType)
            binding.textViewCity.text = weather.cityInfo.city
            binding.textViewProvince.text = weather.cityInfo.parent
            binding.textViewShidu.text = weather.data.shidu
            binding.textViewWendu.text = weather.data.wendu
            val firstDay  = weather.data.forecast.first()
            when (firstDay.type) {
                "晴" -> binding.imageView.setImageResource(R.drawable.sun)
                 "多云" -> binding.imageView.setImageResource(R.drawable.mcloud)
                 "阴" -> binding.imageView.setImageResource(R.drawable.cloud)
                 "雨" -> binding.imageView.setImageResource(R.drawable.rain)
                 "雪" -> binding.imageView.setImageResource(R.drawable.snow)
                 "雷阵雨" -> binding.imageView.setImageResource(R.drawable.thunder)
                else -> binding.imageView.setImageResource(R.drawable.sun)
            }
            val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, weather.data.forecast)
            binding.listView.adapter = adapter

            Log.d("MainActivity2", "${weather.cityInfo.city}")
        }, {
            Log.d("MainActivity2", "$it")
        })
        queue.add(stringRequest)
    }

    }